package com.example.web.sys_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.web.sys_menu.entity.AssignTreeParam;
import com.example.web.sys_menu.entity.AssignTreeVo;
import com.example.web.sys_menu.entity.Menu;
import com.example.web.sys_menu.service.IMenuService;
import com.example.web.sys_user.entity.User;
import com.example.web.sys_user.mapper.UserMapper;
import com.example.web.sys_user.service.IUserService;
import com.example.web.sys_user_role.entity.UserRole;
import com.example.web.sys_user_role.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LS
 * @since 2024-02-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IMenuService menuService;

    @Transactional
    @Override
    public void saveUser(User user) {
        //插入用户信息
        int i = this.baseMapper.insert(user);
        //设置用户的角色
        if (i > 0) {
            //把前端逗号分隔的字符串转为数组
            String[] split = user.getRoleId().split(",");
            if (split.length > 0) {
                List<UserRole> roles = new ArrayList<>();
                for (String s : split) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getUserId());
                    userRole.setRoleId(Long.parseLong(s));
                    roles.add(userRole);
                }
                //保存到用户角色表
                userRoleService.saveBatch(roles);
            }
        }
    }

    @Transactional
    @Override
    public void editUser(User user) {
        //编辑用户信息
        int i = this.baseMapper.updateById(user);
        //设置用户的角色
        if (i > 0) {
            //把前端逗号分隔的字符串转为数组
            String[] split = user.getRoleId().split(",");
            //删除用户原来的角色
            QueryWrapper<UserRole> query = new QueryWrapper<>();
            query.lambda().eq(UserRole::getUserId, user.getUserId());
            userRoleService.remove(query);
            //重新插入
            if (split.length > 0) {
                List<UserRole> roles = new ArrayList<>();
                for (String s : split) {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getUserId());
                    userRole.setRoleId(Long.parseLong(s));
                    roles.add(userRole);
                }
                //保存到用户角色表
                userRoleService.saveBatch(roles);
            }
        }
    }

    @Transactional
    @Override
    public void deleteUser(Long userId) {

        //删除用户
        int i = this.baseMapper.deleteById(userId);
        if (i > 0) {
            //删除角色
            //删除用户原来的角色
            QueryWrapper<UserRole> query = new QueryWrapper<>();
            query.lambda().eq(UserRole::getUserId, userId);
            userRoleService.remove(query);
        }
    }

    @Override
    public AssignTreeVo getAssignTree(AssignTreeParam param) {
        //查询用户的信息
        User user = this.baseMapper.selectById(param.getUserId());
        List<Menu> menuList;
        //判断是否是超级管理员
        if (StringUtils.isNotEmpty(user.getIsAdmin()) && "1".equals(user.getIsAdmin())) {
            //是超级管理员，查询所有的菜单
            menuList = menuService.list();
        } else {
            menuList = menuService.getMenuByUserId(param.getUserId());
        }
        //查询角色原来的菜单
        List<Menu> roleList = menuService.getMenuByRoleId(param.getRoleId());
        List<Long> ids = new ArrayList<>();
        Optional.ofNullable(roleList).orElse(new ArrayList<>())
                .stream()
                .filter(Objects::nonNull)
                .forEach(item -> ids.add(item.getMenuId()));
        //组装返回的数据
        AssignTreeVo vo = new AssignTreeVo();
        vo.setCheckList(ids.toArray());
        vo.setMenuList(menuList);
        return vo;
    }

    //根据用户名查用户
    @Override
    public User loadUser(String username) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.lambda().eq(User::getUsername, username);
        return this.baseMapper.selectOne(query);
    }

}
